<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

/**
 * 前台公共库文件
 * 主要定义前台公共函数库
 */

/**
 * 检测验证码
 * @param  integer $id 验证码ID
 * @return boolean     检测结果
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function check_verify($code, $id = 1){
	$verify = new \Think\Verify();
	return $verify->check($code, $id);
}

/**
 * 获取列表总行数
 * @param  string  $category 分类ID
 * @param  integer $status   数据状态
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function get_list_count($category, $status = 1){
    static $count;
    if(!isset($count[$category])){
        $count[$category] = D('Document')->listCount($category, $status);
    }
    return $count[$category];
}

/**
 * 获取段落总数
 * @param  string $id 文档ID
 * @return integer    段落总数
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function get_part_count($id){
    static $count;
    if(!isset($count[$id])){
        $count[$id] = D('Document')->partCount($id);
    }
    return $count[$id];
}

/**
 * 获取导航URL
 * @param  string $url 导航URL
 * @return string      解析或的url
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function get_nav_url($url){
    switch ($url) {
        case 'http://' === substr($url, 0, 7):
        case '#' === substr($url, 0, 1):
            break;        
        default:
            $url = U($url);
            break;
    }
    return $url;
}

/**
 * 接受json数据
 * */
function php_input(){
    return file_get_contents("php://input");
}

/**
 * 按综合方式输出通信数据
 * @param integer $result 状态码
 * @param string $msg 提示信息
 * @param array $data 数据
 * return string
 */
function api_return($result, $msg = '', $data = false) {
    if(!is_numeric($result)) {
        return '';
    }

    return api_json($result, $msg, $data);
}
/**
 * 按json方式输出通信数据
 * @param integer $result 状态码
 * @param string $msg 提示信息
 * @param array $data 数据
 * return string
 */
function api_json($result, $msg = '', $data = false) {

    if(!is_numeric($result)) {
        return '';
    }

    if($data > 0 || $data === []){
        $message = array(
            'result' => $result,
            'msg' => $msg,
            'data' => $data?$data:[]
        );
    }else{
        $message = array(
            'result' => $result,
            'msg' => $msg,
            'data' => $data?$data:''
        );
    }

    echo json_encode($message);
    exit;
}

/**
 * 获取用户头像地址
 * $uid  integer  用户id
 * */
function get_avatar($uid){
    $user_info = M('user')->field('avatar_img,edit_img')->where(['id' => $uid])->find();

    if($user_info['edit_img'] == 0 && $user_info['avatar_img'] != ''){
        //第三方登录用户还未修改头像
        return M('user')->where(['id' => $uid])->getField('avatar_img');

    }elseif($user_info['edit_img'] != 0){
        //用户修改了头像
        $info = M('user')->alias('u')
            ->join('zb_picture p ON u.edit_img = p.id')
            ->where(['u.id' => $uid])
            ->find();

        return $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$info['path'];
    }elseif($user_info['edit_img'] == 0 && $user_info['avatar_img'] == ''){
        //手机号登录用户未修改头像
        return '';
    }
}

/**
 * 获取直播间在线人数
 * @param  integer $auid 主播id
 */
function get_online_user($auid){
    $count = M('viewer')->where(['auid' => $auid, 'is_room' => 1])->count();
    return $count;
}

/**
 * 是否关注某主播
 * @param int $uid 用户id
 * @param int $cuid 主播id
 */
function is_concern($uid,$cuid){
    $status = M('concern')->where(['uid' => $uid, 'cuid' => $cuid])->getField('status');
    return isset($status)?$status:0;
}

/**
 * 是否守护某主播
 * @param int $uid 用户id
 * @param int $auid 主播id
 */
function is_sh($uid,$auid){
    $map['end_time']  = array('gt',time());
    $count = M('sh_notes')->where($map)->where(['uid' => $uid, 'auid' => $auid])->count();
    return $count?1:0;
}

/**
 * 主播粉丝数
 * @param int $cuid 主播id
 */
function concern_count($cuid){
    $count = M('concern')->where(['cuid' => $cuid, 'status' => 1])->count();
    return $count;
}

/**
 * 取出单张图片
 * @param string $ids 图片id集合
 * */
function get_img($id){
    $path = M('picture')->field('path')->where(['id' => $id])->getField('path');

    if($path){
        return $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$path;
    }else{
        return '';
    }
}

/**
 * 取出多张图片
 * @param string $ids 图片id集合
 * */
function get_pictrues($ids){
    $where['id'] = array('in',$ids);//tp3.2查询语句IN条件
    $list = M('picture')->field('id,path')->where($where)->select();

    foreach($list as $k => $v){
        $list[$k]['path'] = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$v['path'];
    }
    return $list;
}

/**
 * 格式化时间
 * $time  int
 * */
function format_time($time){
    $today = date('Y-m-d');
    $format_time = date('Y-m-d',$time);
    if($today == $format_time){
        return '今天';
    }else{
        return date('m-d',$time);
    }
}

/**
 * 会员开通到期时间
 * @param  int  $month  开通月数
 * $end_year   到期年
 * $over_month   到期月
 * $end_day   到期日
 * return int
 * */
function expire($month){
    $start_year = date('Y');
    $start_month = date('m');
    $start_day = intval(date('d'));
    $start_H = date('H');
    $start_i = date('i');
    $start_s = date('s');

    $end_month = $start_month+$month;

    //结束年计算
    if($end_month > 12){
        //产生跨年
        $over_month = $month - (12-$start_month);//结束的月份
        if($over_month >= 12){
            $add_year = ceil($over_month/12);
            $end_year = $start_year+$add_year;
        }else{
            $end_year = $start_year+1;
        }
    }else{
        $end_year = $start_year;
        $over_month = $start_month+$month;
    }

    $month_day = cal_days_in_month(CAL_GREGORIAN, $over_month, $end_year);
    if($start_day > $month_day){
        $end_day = $month_day;
    }else{
        $end_day = $start_day;
    }

    $expire_date = $end_year.'-'.$over_month.'-'.$end_day.' '.$start_H.':'.$start_i.':'.$start_s;
    return strtotime($expire_date);
}

/**
 * 多维数组排序
 * */
function my_sort($arrays,$sort_key,$sort_order=SORT_ASC,$sort_type=SORT_NUMERIC ){
    if(is_array($arrays)){
        foreach ($arrays as $array){
            if(is_array($array)){
                $key_arrays[] = $array[$sort_key];
            }else{
                return false;
            }
        }
    }else{
        return false;
    }
    array_multisort($key_arrays,$sort_order,$sort_type,$arrays);
    return $arrays;
}

/*****************直播间显示数据封装**********************/
/**
 * 主播个人信息
 * @param int $auid 主播id
 * @param int $uid 用户id
 * */
function zb_user_info($auid,$uid = 0){
    $user_info = M('user')->field('nickname,number')->where(['id' => $auid, 'is_anchor' => 1])->find();
    $avatar_img = get_avatar($auid);
    if($uid){
        $is_concern = is_concern($uid,$auid);
        $is_sh = is_sh($uid,$auid);
    }

    $data = [
        'avatar_img' => $avatar_img,
        'nickname' => $user_info['nickname'],
        'ID' => $user_info['number'],
        'is_concern' => isset($is_concern)?$is_concern:0,
        'is_sh' => isset($is_sh)?$is_sh:0,
    ];

    return $data;
}

/**
 * 贡献度
 * @param int $auid 主播id
 * */
function zb_profit($auid){
    $profit = M('user')->where(['id' => $auid])->getField('profit');
    return $profit;
}

/**
 * 守护人数
 * @param int $auid 主播id
 * */
function zb_sh($auid){
    $map['end_time']  = array('gt',time());
    $list = M('sh_notes')->field('uid')->distinct(true)->where($map)->where(['auid' => $auid])->select();
    return count($list);
}

/**
 * 正在唱的歌曲
 * @param int $auid 主播id
 * */
function singing($auid){
    $music_id = M('ydmusic')->where(['auid' => $auid, 'is_sing' => 1])->order('sing_time desc')->limit(1)->getField('music_id');
    $title = M('music')->where(['id' => $music_id])->getField('title');

    return $title?$title:'';
}

/**
 * 是否开通贵族
 * @param int $uid 用户id
 * */
function zb_gz($uid){
    $map['end_time']  = array('gt',time());
    $count = M('gz_notes')->where($map)->where(['uid' => $uid])->count();
    return $count;
}

/**
 * 未演唱歌曲数量
 * @param int $auid 主播id
 * */
function music_count($auid){
    $count = M('ydmusic')->where(['auid' => $auid, 'is_sing' => 0])->count();
    return $count;
}

/**
 * 未连麦数量
 * @param int $auid 主播id
 * */
function lianmai_count($auid){
    $count = M('lianmai')->where(['auid' => $auid, 'status' => 0])->count();
    return $count;
}

/**
 * pk信息
 * @param int $buid 被pk主播id
 * */
function pk_info($buid){
    $info = M('pk')->alias('p')
        ->field('u.id,u.nickname')
        ->join('zb_user u ON p.uid = u.id')
        ->where(['p.buid' => $buid])
        ->order('u.create_time desc')
        ->find();
    $info['avatar_img'] = get_avatar($info['id']);

    return $info;
}

/*****************直播间显示数据封装**********************/

/**
 * 检测官方是否有新的消息
 * @param $uid   int    当前登录者id
 * @return array   $info有新消息，[]没有新消息
 */
function official_status($uid){
    $db = M('document_about');

    $where = ' a.style = 1 AND d. STATUS = 1 AND ( a.user_id = 0 OR a.user_id = '.$uid.') ';

    $ids = $db->alias('a')
        ->join('wx_document d ON a.id = d.id')
        ->field('a.id')
        ->where($where)
        ->select();

    $document_id = M('official')->field('document_id id')->where(['uid' => $uid])->select();

    foreach($ids as $k => $v){
        foreach($document_id as $key => $val){
            if($v['id'] == $val['id']){
                unset($ids[$k]);
            }
        }
    }

    if($ids){
        return $ids;//需要入库到official的数据
    }else{
        return [];
    }

}

/******************未读消息数模块封装***********************/
/**
 * 未读的系统消息数
 * */
function mess_count($uid){
    $list = M('message')->field('id')->where(" (uid = ". $uid ." or uid = 0) and type = 1 ")->select();

    $m_list = M('official')->field('mid')->where(['uid' => $uid])->select();

    if(count($m_list) == 0) return count($list);

    foreach($m_list as $k => $v){
        foreach ($list as $key => $val){
            if($val['id'] == $v['mid']){
                unset($list[$key]);
            }
        }
    }
    return count($list);//未读系统消息数
}

/**
 * 主播未读的新增关注消息数
 * */
function zb_concern_mess_count($buid){
    $list = M('message')->field('id')->where(" buid = ". $buid ." and type = 2 ")->select();

    $m_list = M('official')->field('mid')->where(['uid' => $buid])->select();

    if(count($m_list) == 0) return $list?$list:0;

    foreach($m_list as $k => $v){
        foreach ($list as $key => $val){
            if($val['id'] == $v['mid']){
                unset($list[$key]);
            }
        }
    }
    return $list;
}

/**
 * 普通用户的新增关注消息数
 * */
function user_concern_mess_count($buid){
    $list = M('message')->field('id')->where(" buid = ". $buid ." and type = 3 ")->select();

    $m_list = M('official')->field('mid')->where(['uid' => $buid])->select();

    if(count($m_list) == 0) return $list?$list:0;

    foreach($m_list as $k => $v){
        foreach ($list as $key => $val){
            if($val['id'] == $v['mid']){
                unset($list[$key]);
            }
        }
    }
    return $list;
}
/******************未读消息数模块封装***********************/

/**
 * 首页数据格式
 * @param $type string 类型
 * @param $ids  array  主播id集合
 * */
function rooms_data_bak($type = '',$ids = []){
    if($type == 'index'){
        $list = M('anchor')->field('id,number,play_url,push_url,create_time,temp_room_id,lm_play_url')->where(['is_show' => 2])->select();
    }else{
        $map['auid'] = array('IN',$ids);
        $list = M('anchor')->field('id,number,play_url,push_url,create_time,temp_room_id,lm_play_url')->where($map)->select();
    }

    if($list){
//        $result = [
//            'code' => 0,
//            'message' => '请求成功'
//        ];

        $roomInfo = "{'title':'自定义描述内容','frontcover':'','location':''}";
        foreach($list as $k => $v){
            $room[$k]['roomID'] = $v['temp_room_id'];
            $room[$k]['roomInfo'] = '';
            $room[$k]['roomCreator'] = $v['number'];
            $room[$k]['mixedPlayURL'] = $v['play_url'];
            $room[$k]['audienceCount'] = 0;
            $pushers = [
                "userID" => $v['number'],
                "userName" => $v['number'],
                "userAvatar" => "",
                "accelerateURL" => $v['lm_play_url']//拉流地址
            ];

            $room[$k]['pushers'][] = $pushers;
        }
//        $result['rooms'] = $room;
    }else{
//        $result = [
//            'code' => 0,
//            'message' => '请求成功',
//            'rooms' => []
//        ];
//        $result['rooms'] = [];
    }
    return $room;
}

function advert_room($auid = 0){
    if(empty($auid)){
        $room = [
            'roomID' => '',
            'roomInfo' => '',
            'roomCreator' => '',
            'mixedPlayURL' => '',
            'audienceCount' => '',
            'userID' => '',
            'userName' => '',
            'userAvatar' => '',
            'accelerateURL' => '',
            'auid' => '',
            'skill_id' => '',
            'anchor_time' => '',
            'funs_num' => '',
            'is_show' => '',
            'img' => '',
            'nickname' => '',
            'is_one' => ''
        ];
    }else{
        $info = M('anchor')->field('id,auid,number,play_url,push_url,create_time,temp_room_id,lm_play_url')->where(['auid' => $auid])->find();

        $room['roomID'] = $info['temp_room_id']?$info['temp_room_id']:'';
        $room['roomInfo'] = '';
        $room['roomCreator'] = $info['number']?$info['number']:'';
        $room['mixedPlayURL'] = $info['play_url']?$info['play_url']:'';
        $room['audienceCount'] = "0";
        $room['userID'] = $info['number']?$info['number']:'';
        $room['userName'] = $info['number']?$info['number']:'';
        $room['userAvatar'] = '';
        $room['accelerateURL'] = $info['lm_play_url']?$info['lm_play_url']:'';//拉流地址

        $number = $info['number'];
        $info = M('user')->field('id as auid,skill_id,anchor_time,funs_num,cover,nickname')->where(['number' => $number])->find();

        $is_show = M('anchor')->where(['number' => $number])->getField('is_show');//查询是否开播

        $room['auid'] = $info['auid']?$info['auid']:"0";
        $room['skill_id'] = $info['skill_id']?$info['skill_id']:"0";
        $room['anchor_time'] = $info['anchor_time']?$info['anchor_time']:"0";
        $room['funs_num'] = $info['funs_num']?$info['funs_num']:"0";
        $room['is_show'] = $is_show?$is_show:"0";
        $room['img'] = get_img($info['cover']);//直播封面图
        $room['nickname'] = $info['nickname']?$info['nickname']:'';
        $is_one = M('anchor')->where(['number' => $number])->getField('is_one');
        $room['is_one'] = $is_one?$is_one:"0";

    }

    return $room;

}

//二维数组转化为字符串，中间用,隔开
function arr_to_str($arr) {
    foreach ($arr as $v) {
        $v = join(",",$v); // 可以用implode将一维数组转换为用逗号连接的字符串，join是别名
        $temp[] = $v;
    }
    $t = '';
    foreach ($temp as $v) {
        $t .= $v.",";
    }
    $t = substr($t, 0, -1); // 利用字符串截取函数消除最后一个逗号
    return $t;
}


/**
 * 首页数据格式
 * @param $type string 类型
 * @param $ids  array  主播id集合
 * */
function rooms_data($type = '',$ids = []){
    if($type == 'index'){
        $list = M('anchor')->field('id,number,play_url,push_url,create_time,temp_room_id,lm_play_url')->where(['is_show' => 2])->select();
    }elseif($type == 'lately'){
        //注意：最近观看ids为当前登陆者的id
        $list = M('lately l')
            ->join('zb_anchor a ON l.cuid = a.auid')
            ->field('l.cuid')
            ->where(['l.uid' => $ids])
            ->order('a.is_show desc,l.create_time desc')
            ->select();

        foreach($list as $k => $v){
            $list[$k] = M('anchor')->field('id,auid,number,play_url,push_url,create_time,temp_room_id,lm_play_url')->where(['auid' => $v['cuid']])->find();
            unset($list[$k]['cuid']);
        }
    }else{
        $map['auid'] = array('IN',$ids);
        $list = M('anchor')->field('id,auid,number,play_url,push_url,create_time,temp_room_id,lm_play_url')->where($map)->select();
    }

    if($list){
        foreach($list as $k => $v){
            $room[$k]['roomID'] = $v['temp_room_id'];
            $room[$k]['roomInfo'] = '';
            $room[$k]['roomCreator'] = $v['number'];
            $room[$k]['mixedPlayURL'] = $v['play_url'];
            $room[$k]['audienceCount'] = "0";
            $room[$k]['userID'] = $v['number'];
            $room[$k]['userName'] = $v['number'];
            $room[$k]['userAvatar'] = '';
            $room[$k]['accelerateURL'] = $v['lm_play_url'];//拉流地址

            $number = $v['number'];
            $info = M('user')->field('id as auid,skill_id,anchor_time,funs_num,cover,nickname,lng,lat')->where(['number' => $number])->find();

            $is_show = M('anchor')->where(['number' => $number])->getField('is_show');//查询是否开播

            $room[$k]['auid'] = $info['auid']?$info['auid']:"0";
            $room[$k]['skill_id'] = $info['skill_id']?$info['skill_id']:"0";
            $room[$k]['anchor_time'] = $info['anchor_time']?$info['anchor_time']:"0";
            $room[$k]['funs_num'] = $info['funs_num']?$info['funs_num']:"0";
            $room[$k]['is_show'] = $is_show?$is_show:"0";
            $room[$k]['img'] = get_img($info['cover']);//直播封面图
            $room[$k]['nickname'] = $info['nickname']?$info['nickname']:'';
            $is_one = M('anchor')->where(['number' => $number])->getField('is_one');
            $room[$k]['is_one'] = $is_one?$is_one:"0";
        }
    }
    return $room;
}


/**
 * 贵族信息
 * @param int $uid  用户id
 * */
function gz_rank($uid){
    $info = M('gz_notes')->field('level_id,end_time')->where(['uid' => $uid])->order('create_time desc')->find();
    $img_info = M('gz_level')->field('name,img')->where(['id' => $info['level_id']])->find();
    $img = get_img($img_info['img']);

    if($info['end_time'] > time()){
        $time = $info['end_time']-time();
        $info = [
            'day' => floor($time/(24*3600)),
            'img' => $img,
            'name' => $img_info['name']
        ];
    }else{
        $info = [
            'day' => 0,
            'img' => '',
            'name' => ''
        ];
    }

    return $info;
}

/**
 * 守护信息
 * @param int $level_id  等级id
 * */
function sh_rank($level_id){
    $info = M('sh_level')->where(['id' => $level_id])->find();
    return $info;
}

/**
 * 计算两经纬度之间的距离
 * @param $lng_a 主播经度
 *        $lat_a 主播纬度
 *        $lnt_b 用户经度
 *        $lat_b 用户纬度
 * */
function getDistance_map($lng_a, $lat_a, $lng_b, $lat_b) {
    //R是地球半径（米）

    $R = 6377830;

    $pk = doubleval(180 / 3.1415926);

    $a1 = doubleval($lat_a / $pk);
    $a2 = doubleval($lng_a / $pk);
    $b1 = doubleval($lat_b / $pk);
    $b2 = doubleval($lng_b / $pk);

    $t1 = doubleval(cos($a1) * cos($a2) * cos($b1) * cos($b2));
    $t2 = doubleval(cos($a1) * sin($a2) * cos($b1) * sin($b2));
    $t3 = doubleval(sin($a1) * sin($b1));
    $tt = doubleval(acos($t1 + $t2 + $t3));

    return round($R*$tt/1000,1);
}

/**
 * 数组分页函数  核心函数  array_slice
 * 用此函数之前要先将数据库里面的所有数据按一定的顺序查询出来存入数组中
 * $count   每页多少条数据
 * $page   当前第几页
 * $array   查询出来的所有数组
 */
function page_array($count,$page,$array){
    $page=(empty($page))?'1':$page; #判断当前页面是否为空 如果为空就表示为第一页面
    $start=($page-1)*$count; #计算每次分页的开始位置

    $pagedata=array_slice($array,$start,$count);
    return $pagedata;  #返回查询数据
}


/**
 * base64 多图上传
 * $uid 用户id
 * $imgs_file 图片 base64
 */
function  base64_all_img($imgs_file="")
{
    if (!is_dir("Uploads/Picture/" . date("Y-m-d"))) {
        mkdir("Uploads/Picture/" . date("Y-m-d"));
    }

    $img = explode('|', $imgs_file);
    if ($img) {
        $img_id = '';
        foreach ($img as $v) {
            //判断是否上传过
            $base64_img = trim($v);
            if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)) {
                //判断是否上传过
                $map = array('md5' => md5($base64_img),'sha1' => sha1($base64_img));
                $res_img_id=M("Picture")->where($map)->getField('id');

                if($res_img_id){
                    $img_id .= $res_img_id . ",";
                }else {
                    $type = $result[2];
                    if (in_array($type, array('pjpeg', 'jpeg', 'jpg', 'gif', 'bmp', 'png'))) {
                        $new_file = "Uploads/Picture/" . date("Y-m-d") . "/" . time() . rand(1000,9999) . '.' . $type;

                        $base64_1 = str_replace($result[1], '', $base64_img);
                        if (file_put_contents($new_file, base64_decode($base64_1))) {
                            $pic = '/' . $new_file;
                            $nnpic = $pic;
                            $img_arr['path'] = $nnpic;
                            $img_arr['status'] = 1;
                            $img_arr['create_time'] = time();
                            $img_arr['md5'] = md5($base64_img);
                            $img_arr['sha1'] = sha1($base64_img);
                            $picture_id = D('picture')->add($img_arr);
                            $img_id .= $picture_id . ",";
                        } else {
                            return api_return(2,'保存失败');
                        }

                    } else {
                        //文件类型错误
                        return api_return(2,'保存失败');
                    }
                }
            } else {
                //文件错误
                return api_return(2,'base64错误');
            }
        }
    } else {
        return api_return(2,'参数错误');
    }
    return $img_id;
}

/**
 * base64 单图上传
 * $cover_file 图片 base64
 * $img_name 返回提示
 */
function base64_one_img ($cover_file=""){

    if (!is_dir("Uploads/Picture/" . date("Y-m-d"))) {
        mkdir("Uploads/Picture/" . date("Y-m-d"));
    }

    $base64_img = trim($cover_file);
    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)) {

        //判断是否上传过
        $map = array('md5' => md5($base64_img),'sha1' => sha1($base64_img));
        $res_img_id = M("picture")->where($map)->getField('id');

        if($res_img_id){
            return $res_img_id;
        }
        $type = $result[2];

        if (in_array($type, array('pjpeg', 'jpeg', 'jpg', 'gif', 'bmp', 'png'))) {
            $cover_file = str_replace($result[1],'',$cover_file);
            $cover_aid = base64_decode($cover_file);

            $cover_path = "Uploads/Picture/" . date("Y-m-d") . "/" . time() . rand(1000,9999) . '.' . $type;

            $cover_result = file_put_contents($cover_path, $cover_aid);//保存图片，返回的是字节数
            if ($cover_result) {

                $cover_arr['path'] = "/" . $cover_path;
                $cover_arr['status'] = 1;
                $cover_arr['md5'] = md5($cover_file);
                $cover_arr['sha1'] = sha1($cover_file);
                $cover_arr['create_time'] = time();
                $cover_id = D('picture')->add($cover_arr);

                if (!$cover_id) {
                    unlink($cover_path);
                    return api_return(2,'保存失败');
                }
            } else {
                return api_return(2,'保存失败');
            }
            return $cover_id;
        }else{
            //文件类型错误
            return api_return(2,'文件类型错误');
        }
    }else{
        //文件错误
        return api_return(2,'base错误');
    }
}


/**
 * base64 单图上传
 * $cover_file 图片 base64
 * $img_name 返回提示
 */
function base64_one_img_test($cover_file=""){

    if (!is_dir("Uploads/Picture/" . date("Y-m-d"))) {
        mkdir("Uploads/Picture/" . date("Y-m-d"));
    }

    $base64_img = trim($cover_file);
    dump($base64_img);exit;
    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)) {
        //判断是否上传过
        $map = array('md5' => md5($base64_img),'sha1' => sha1($base64_img));
        $res_img_id = M("picture")->where($map)->getField('id');

        if($res_img_id){
            return $res_img_id;
        }
        $type = $result[2];

        if (in_array($type, array('pjpeg', 'jpeg', 'jpg', 'gif', 'bmp', 'png'))) {
            $cover_file = str_replace($result[1],'',$cover_file);
            $cover_aid = base64_decode($cover_file);

            $cover_path = "Uploads/Picture/" . date("Y-m-d") . "/" . time() . rand(1000,9999) . '.' . $type;

            $cover_result = file_put_contents($cover_path, $cover_aid);//保存图片，返回的是字节数
            if ($cover_result) {

                $cover_arr['path'] = "/" . $cover_path;
                $cover_arr['status'] = 1;
                $cover_arr['md5'] = md5($cover_file);
                $cover_arr['sha1'] = sha1($cover_file);
                $cover_arr['create_time'] = time();
                $cover_id = D('picture')->add($cover_arr);

                if (!$cover_id) {
                    unlink($cover_path);
                    return api_return(2,'保存失败');
                }
            } else {
                return api_return(2,'保存失败');
            }
            return $cover_id;
        }else{
            //文件类型错误
            return api_return(2,'文件类型错误');
        }
    }else{
        //文件错误
        return api_return(2,'base错误');
    }
}


